package com.permissionmanager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.permissionmanager.entity.*;
import com.permissionmanager.exception.ServiceException;
import com.permissionmanager.mapper.PermMapper;
import com.permissionmanager.mapper.PermRoleMapper;
import com.permissionmanager.mapper.RoleMapper;
import com.permissionmanager.mapper.UserMapper;
import com.permissionmanager.service.UserService;
import com.permissionmanager.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * user业务层
 *
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final PermRoleMapper permRoleMapper;
    private final PermMapper permMapper;

    // 通过用户名查询用户信息
    private User findByUserName(String username,String phone) {
        return userMapper.findByUser(null, username,phone);
    }

    /**
     * 新增
     * @param user 用户信息（username、password、phone）
     */
    @Override
    public void add(User user) {
        User dbUser = findByUserName(user.getUsername(),user.getPhone());
        if (dbUser != null) {
            throw new ServiceException("用户已存在！");
        }
        if(StrUtil.isBlank(user.getPassword())){
            throw new ServiceException("密码格式错误！");
        }
        if(StrUtil.isBlank(user.getPhone()) || StrUtil.isBlank(user.getUsername())){
            throw new ServiceException("账号或手机号为空!");
        }
        if(user.getPhone().length() != 11 || user.getUsername().length() < 3 || user.getPassword().length() < 3){
            throw new ServiceException("账号或手机号格式错误!");
        }
        if(StrUtil.isBlank(user.getName())){
            user.setName(user.getUsername());
        }
        userMapper.add(user);
    }



    /**
     * 登录
     * @param user 用户信息（username、password）
     */
    @Override
    public User login(User user) {
        // 通过用户名查询用户信息
        User dbUser = findByUserName(user.getUsername(),null);
        if (dbUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (!dbUser.getPassword().equals(user.getPassword())) {
            throw new ServiceException("密码错误！");
        }
        String token = JwtUtil.createToken(String.valueOf(dbUser.getId()), dbUser.getPassword());
        // 获取用户权限
        List<Role> role = roleMapper.findRole(null, dbUser.getRole());
        if (role == null) {
            throw new ServiceException("系统错误");
        }
        // 通过role表的perm_role_id查perm_role表的role_id的数据
        List<PermRole> permRoleList = permRoleMapper.findPermRole(null, role.get(0).getPermRoleId());
        List<Perm> permList = new ArrayList<>();
        // 数据为空查所有
        if (permRoleList != null && !permRoleList.isEmpty()) {
            for (PermRole permRole : permRoleList) {
                // 通过perm_id查perm表数据，并添加到permList中
                List<Perm> perm = permMapper.findPerm(permRole.getPermId(), null, null, null, 1);
                permList.add(perm.get(0));
            }
        } else {
            permList = permMapper.findPerm(null,null,null,null,1);
        }
        // 包装数据
        ArrayList<Perm> permList1 = new ArrayList<>();
        // 父级
        for (Perm perm : permList) {
            if (perm.getIsOne() == 0 && perm.getPNo() == null) {
                permList1.add(perm);
            }
        }
        // 子级
        for (Perm perm1 : permList1) {
            ArrayList<Perm> permList2 = new ArrayList<>();
            for (Perm perm : permList) {
                if (StrUtil.equals(perm1.getPath(),perm.getPNo())) {
                    permList2.add(perm);
                }
            }
            perm1.setPerms(permList2);
        }
        // 一级菜单
        for (Perm perm : permList) {
            if (perm.getIsOne() == 1) {
                permList1.add(perm);
            }
        }
        dbUser.setPermList(permList1);
        dbUser.setToken(token);
        return dbUser;
    }

    /**
     * 忘记密码
     * @param user 用户信息（phone、username、password）
     */
    @Override
    public void forgetPwd(User user) {
        User dbUser = userMapper.findByUser(null, user.getUsername(), user.getPhone());
        if (dbUser == null) {
            throw new ServiceException("账号或手机号错误！");
        }
        // 调用修改功能
        user.setName(user.getUsername());
        user.setId(dbUser.getId());
        update(user);
    }

    /**
     * 修改
     * @param user （phone、id）
     */
    @Override
    public void update(User user) {
        if(user.getPhone().length() != 11 || StrUtil.isBlank(user.getPhone()) || user.getPassword().length() < 3){
            throw new ServiceException("手机号或密码格式错误!");
        }
        userMapper.update(user);
    }

    /**
     * 分页查询
     */
    @Override
    public Page<User> findPage(Integer pageNum, Integer pageSize, String username, String name) {
        Integer skipNum = (pageNum - 1) * pageSize;
        Page<User> page = new Page<>();
        List<User> list = userMapper.findPage(skipNum, pageSize, username, name);
        page.setTList(list);
        page.setTotal(list.size());
        return page;
    }

    /**
     * 删除
     * @param id 传入的id
     */
    @Override
    public void del(Integer id) {
        userMapper.del(id);
    }


}
